package servlet;

import dao.BlogDao;
import dao.UserDao;
import model.Blog;
import model.User;
import utils.JSONUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author : niu niu
 * @version : 1.0.0
 * @date : 2023/4/10 10:16
 */
@WebServlet("/user")
public class UserServlet extends HttpServlet {
    BlogDao blogDao = new BlogDao();
    UserDao userDao = new UserDao();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        resp.setContentType("application/json;charset=utf8"); 下面要用到text/html
        resp.setCharacterEncoding("utf8");
        HttpSession session = req.getSession(false);

        if (session==null || session.getAttribute("user")==null){
            resp.getWriter().write("用户不存在");
            return;
        }
        User user = (User) session.getAttribute("user");
        if (user == null || user.getId() <= 0){
            resp.getWriter().write("用户不存在");
            return;
        }

        resp.setContentType("application/json");
        String blogIdParam = req.getParameter("blogId");
        if (blogIdParam == null || "".equals(blogIdParam)){
            //列表页
            resp.getWriter().write(JSONUtils.toJSON(user));
        }else {
            //详情页
            Integer blogId = Integer.parseInt(blogIdParam);
            Blog blog = blogDao.getBlogByID(blogId);
            User author = userDao.selectById(blog.getUserId());
            if (author.getId() == user.getId()){
                author.setIsYourBlog(1);
            }
            resp.getWriter().write(JSONUtils.toJSON(author));
        }
    }
}
